import { defineStore } from 'pinia';
import axios from '../api/request.ts';

export const useUserStore = defineStore('user', {
    state: () => ({
        userId: localStorage.getItem('userId') || '',
        userType: localStorage.getItem('userType') || '',
        users: [] as any[],
    }),
    actions: {
        setUser(userId: string, userType: string) {
            this.userId = userId;
            this.userType = userType;
            localStorage.setItem('userId', userId);
            localStorage.setItem('userType', userType);
        },
        logout() {
            this.userId = '';
            this.userType = '';
            localStorage.removeItem('userId');
            localStorage.removeItem('userType');
        },
        async fetchUsers() {
            try {
                const response = await axios.get('/users');
                this.users = response.data;
            } catch (error) {
                console.error('Error fetching users:', error);
            }
        },
        async deleteUser(userId: number) {
            await axios.delete(`/users/${userId}/delete`);
            this.fetchUsers();
        },
        async updateUserType(userId: number, userType: string) {
            try {
                await axios.put(`/users/${userId}`,
                    { userType },
                    { headers: { 'Content-Type': 'application/json' } }
                );
                this.fetchUsers();
            } catch (error) {
                console.error('Error updating user type:', error);
            }
        },
    },
});
